package iu.gq.db;

import iu.gq.db.items.ChapterDetail;
import iu.gq.db.items.ChapterItem;
import iu.gq.template.GQApplication;

import java.util.List;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import com.gq.utils.FileHelper;

public abstract class DatabaseHelper extends SQLiteOpenHelper {

	public static final String DBNAME = "story";
	public static final String DBPATH = "/data/data/"+GQApplication.getContext().getPackageName()+"/databases/"+DBNAME;
	public static final int VERSION = 1;
	protected Context mContext;
	protected SQLiteDatabase mDb;
	
	public DatabaseHelper(Context context) {
		super(context, DBNAME, null, VERSION);
		mContext = context;
	}
	
	public DatabaseHelper(Context context, String dbName, CursorFactory factory,
			int version) {
		super(context, dbName, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		onCreate(db);
	}
	
	public void createDatabase() {
		if (!isExistDb()) {
			getReadableDatabase();
			copyDatabase();
		}
	}
	
	public void openDatabase() {
		mDb = SQLiteDatabase.openDatabase(DBPATH, null, SQLiteDatabase.OPEN_READWRITE); 
	}
	
	public SQLiteDatabase getDatabase() {
		return SQLiteDatabase.openDatabase(DBPATH, null, SQLiteDatabase.OPEN_READONLY);
	}
	
	private void copyDatabase() {
		FileHelper fileHelper = FileHelper.getInstance(mContext);
		if (fileHelper.isExistsFileAsset(DBNAME)) {
			fileHelper.copy(DBNAME, DBPATH);
		} else {
			fileHelper.mergeAndCopy(DBNAME, DBPATH);
		}
	}
	
	public boolean isExistDb() {
		boolean ret = false;
		try {
			SQLiteDatabase db = SQLiteDatabase.openDatabase(DBPATH, null, SQLiteDatabase.OPEN_READONLY);
			if (db != null) {
				db.close();
				ret = true;
			}
		} catch(SQLiteException e) {
			e.printStackTrace();
		}
		return ret;
				
	}

	@Override
	public synchronized void close() {
		if (mDb != null) {
			if (mDb.isOpen()) mDb.close();
		}
		super.close();
	}

	public abstract List<ChapterDetail> getAllChapterDetails();
	
	public abstract List<ChapterItem> getAllChapterItems();

	public abstract ChapterDetail getChapterDetailById(String Id);
	
	public abstract ChapterItem getChapterItemById(String Id);
}
